<template>
    <div class="content">
        <div class="header-content">
            <el-form id="header-query" label-width="110px" ref="searchParam" :model="searchParam">
                <el-form-item label="发送开始日期" prop="startDate">
                    <el-date-picker
                        v-model="searchParam.startDate"
                        type="date"
                        size="mini"
                        style="width: 100%"
                        value-format="yyyyMMdd"
                        format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="发送结束日期" prop="endDate">
                    <el-date-picker
                        v-model="searchParam.endDate"
                        type="date"
                        size="mini"
                        style="width: 100%"
                        value-format="yyyyMMdd"
                        format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="模板类型" prop="noticeType">
                    <el-select v-model="searchParam.noticeType" filterable size="mini" clearable>
                        <el-option v-for="(value, key) in Dict.noticeTypePojo" :key="key" :label="value" :value="key"> </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="发送人" prop="operatorNo">
                    <el-input size="mini" v-model="searchParam.operatorNo" clearable></el-input>
                </el-form-item>
            </el-form>
            <div>
                <el-button type="primary" size="mini" @click="handleButton('search')">查询</el-button>
            </div>
        </div>
        <div class="noOpened">
            <RiskTableP
                :tableConfig="tableConfig"
                :tableData="tableData"
                :column="tableColumns"
                :paging="paging"
                v-loading="tableLoading"
                @page-change="getTableData"
            >
                <template #operation="scope">
                    <RiskIconButton type="primary" icon="el-icon-view" topTitle="查看" @on-click="handleBtn('look', scope.row)"></RiskIconButton>
                </template>
            </RiskTableP>
        </div>
        <yh-dialog
            :title="'历史发送记录详细信息'"
            :visible.sync="recordDetailVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="1000px"
            drag
            class="record_detail"
        >
            <el-form label-width="130px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="发送批次号:">
                            <el-input v-model="recordForm.recordBatchId" size="mini" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="模板类型:">
                            <el-select v-model="recordForm.noticeType" placeholder="请选择" size="mini" disabled>
                                <el-option v-for="(value, key) in Dict.noticeTypePojo" :key="key" :label="value" :value="key"> </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="计划发送时点:">
                            <el-time-picker v-model="recordForm.startTime" value-format="HHmm" format="HH:mm" size="mini" disabled> </el-time-picker>
                        </el-form-item>
                        <el-form-item label="接收用户:">
                            <el-select placeholder="请选择" multiple filterable collapse-tags v-model="recordForm.noticeUser" size="mini">
                                <el-option
                                    v-for="item in userList"
                                    :key="item.userCode"
                                    :label="item.userName + ' ' + item.userNickName"
                                    :value="item.userCode"
                                    disabled
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="发送时间:">
                            <el-date-picker
                                v-model="recordForm.sendDateTime"
                                type="datetime"
                                format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyyMMddHHmmss"
                                size="mini"
                                disabled
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="规则编码">
                            <el-input v-model="recordForm.ruleId" disabled size="mini" />
                        </el-form-item>
                        <el-form-item label="数据生成类型:">
                            <template slot="label">
                                <span style="font-size:12px">
                                    <el-tooltip>
                                        <div slot="content">自动计算：每天系统自动风控计算；手工计算：由人为触发，在功能页面点击计算。</div>
                                        <i class="el-icon-question"></i>
                                    </el-tooltip>
                                    数据生成类型:
                                </span>
                            </template>
                            <el-select v-model="recordForm.calcType" placeholder="请选择" filterable disabled size="mini">
                                <el-option v-for="(value, key) in Dict.calcTypePojo" :key="key" :label="value" :value="key"> </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="执行方式:">
                            <el-select placeholder="请选择" filterable v-model="recordForm.executionMethod" disabled size="mini">
                                <el-option v-for="(value, key) in Dict.executionMethodPojo" :key="key" :label="value" :value="key"> </el-option>
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="最近一次发送时间:">
                            <el-date-picker
                                v-model="recordForm.deliveryDateTime"
                                type="datetime"
                                format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyyMMddHHmmss"
                                disabled
                                size="mini"
                            >
                            </el-date-picker>
                        </el-form-item> -->
                        <el-form-item label="抄送用户:">
                            <el-select placeholder="请选择" multiple filterable collapse-tags v-model="recordForm.noticeCCuser" size="mini">
                                <el-option
                                    v-for="item in userListTemp"
                                    :key="item.userCode"
                                    :label="item.userName + ' ' + item.userNickName"
                                    :value="item.userCode"
                                    disabled
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="发送状态:">
                            <el-select v-model="recordForm.sendStatus" disabled size="mini">
                                <el-option v-for="(value, key) in Dict.sendStatusPojo" :key="key" :label="value" :value="key"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="规则名称:">
                            <el-input v-model="recordForm.ruleName" disabled size="mini" />
                        </el-form-item>
                        <el-form-item label="通知日历类型:">
                            <el-select v-model="recordForm.dateType" placeholder="请选择" filterable disabled size="mini">
                                <el-option v-for="(value, key) in Dict.dateTypePojo" :key="key" :label="value" :value="key"> </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="接收角色:">
                            <el-select placeholder="请选择" multiple filterable collapse-tags v-model="recordForm.notifier" size="mini">
                                <el-option
                                    v-for="item in roleInfo"
                                    :key="item.roleCode"
                                    :label="item.roleCode + ' ' + item.roleName"
                                    :value="item.roleCode"
                                    disabled
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="发送人:">
                            <el-input v-model="recordForm.operatorNo" disabled size="mini" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="recordDetailVisible = false"> 取 消 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { HistorySendListReqVO } from '../../vo/warning-notice';
import API from '../../api/warning-notice';
import { PageVO, TableConfigVO, VueObject } from '@/common/vo';
import WarningNotice from '../../dict/warning-notice';
import { changeOptions, dateFormat, timeFormat } from '@/utils/tools';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import WarningNoticeDetailStaticRiskDisposal from '../warning-notice-detail-static-risk-disposal.vue';
import * as moment from 'moment';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({ name: 'HistorySendList', components: { RiskTableP, RiskIconButton, WarningNoticeDetailStaticRiskDisposal } })
export default class HistorySendList extends Vue {
    @Prop() activeValue: string;
    Dict = new WarningNotice();
    tableColumns: any = [
        {
            type: 'seq',
            width: 50,
            title: '序号',
        },
        {
            title: '发送批次号',
            field: 'recordBatchId',
            minWidth: 100,
        },
        {
            title: '规则编码',
            field: 'ruleId',
            minWidth: 90,
        },
        {
            title: '规则名称',
            field: 'ruleName',
            minWidth: 120,
        },
        {
            title: '模板类型',
            field: 'noticeType',
            minWidth: 110,
            render: value => this.Dict.noticeTypePojo[value],
        },
        {
            title: '数据生成类型',
            field: 'calcType',
            minWidth: 120,
            render: value => this.Dict.calcTypePojo[value],
        },
        {
            title: '通知日历类型',
            field: 'dateType',
            minWidth: 120,
            render: value => this.Dict.dateTypePojo[value],
        },
        {
            title: '计划发送时点',
            field: 'startTime',
            minWidth: 120,
            render: value => timeFormat(value, false, 'HH:mm', 'HHmm') || '--',
        },
        {
            title: '执行方式',
            field: 'executionMethod',
            minWidth: 90,
            render: value => this.Dict.executionMethodPojo[value],
        },
        {
            title: '接收角色',
            field: 'notifierName',
            minWidth: 90,
        },
        {
            title: '接收用户',
            field: 'noticeUserName',
            minWidth: 90,
        },
        {
            title: '抄送用户',
            field: 'noticeCCuserName',
            minWidth: 90,
        },
        // {
        //     title: '最近一次发送时间',
        //     field: 'sendDate',
        //     minWidth: 150,
        //     render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.sendTime)).trim(),
        // },
        {
            title: '发送人',
            field: 'operatorNo',
            minWidth: 90,
        },
        {
            title: '发送时间',
            field: 'sendDate',
            minWidth: 150,
            render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.sendTime)).trim(),
        },
        {
            title: '发送状态',
            field: 'sendStatus',
            minWidth: 90,
            render: value => this.Dict.sendStatusPojo[value],
        },
        {
            title: '操作',
            field: 'operation',
            minWidth: 80,
            align: 'center',
            fixed: 'right', // 添加？
        },
    ];

    requestTableMethodName: any = API.historySendList;

    isFirst: boolean = true;

    tableConfig: TableConfigVO = {
        rowKey: 'recordId',
    };

    tableData: any[] = [
        {
            recordId: '20231101001',
            entryNum: 20,
            ruleId: 'YH782',
            ruleName: '测试处置1',
            calcType: '0',
            createDate: 20231009,
            createTime: 101910,
            createUser: 'administrator',
            limitTimes: 1,
            // modifyDate: 20231009,
            // modifyTime: 103048,
            sendDate: 20231009,
            sendTime: 103048,
            modifyUser: 'administrator',
            noticeTimes: [],
            noticeType: '14',
            noticeUser: ['GY-dsssssssss', '541'],
            noticeCCuser: ['541'],
            notifier: ['YH102', 'YH121'],
            scheduleType: '0',
            startTime: 1018,
            sendStatus: '0',
            dateType: '0',
            executionMethod: '0',
            operatorNo: '管理员',
        },
    ];

    paging: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    searchParam: HistorySendListReqVO = {
        startDate: moment(new Date())
            .subtract(1, 'days')
            .format('YYYYMMDD'),
        endDate: moment(new Date())
            .subtract(1, 'days')
            .format('YYYYMMDD'),
        noticeType: '',
        operatorNo: '',
    };

    private userList = []; // 用户列表

    private userListTemp = []; // 抄送用户

    private roleInfo = []; // 角色列表

    tableLoading: boolean = false;
    recordForm: any = {};
    curRecord: any = {};
    recordDetailVisible: boolean = false;

    @Watch('activeValue', { immediate: true })
    async handleActiveValue() {
        if (this.activeValue === 'history-send-list') {
            if (this.isFirst) {
                this.getTableData();
                this.isFirst = false;
                this.getRoleInfo();
                this.getUserList();
            }
        }
    }

    // 获取通知角色数据
    private getRoleInfo(): void {
        this.$axios.get('/role/query/all').then((res: any) => {
            this.roleInfo = [];
            for (let item of res) {
                if (item.sourceType === '1') {
                    this.roleInfo.push(item);
                }
            }
        });
    }

    private getUserList(): void {
        this.$axios.get('/userManage/user/list').then((res: any) => {
            // if (res) {
            this.userList = res || [];
            this.userListTemp = JSON.parse(JSON.stringify(res)) || [];
            // }
        });
    }

    // 下拉框数据置顶
    private changeAccountControlValue(val: any = [], field): void {
        // 下拉框选中数据置顶
        if (field == 'noticeUser') {
            this.userList = changeOptions(val, this.userList, 'userCode');
        } else if (field == 'noticeCCuser') {
            this.userListTemp = changeOptions(val, this.userListTemp, 'userCode');
        } else if (field == 'notifier') {
            this.roleInfo = changeOptions(val, this.roleInfo, 'roleCode');
        }
    }

    /**
     * 操作行
     */
    async handleButton(type) {
        if (type == 'search') {
            this.paging.currentPage = 1;
            this.getTableData();
        } else if (type == 'refresh') {
            this.paging.currentPage = 1;
            await this.getTableData();
            this.yh_message_success('刷新成功！');
        }
    }

    /**
     * 表格数据
     */
    getTableData() {
        this.tableLoading = true;
        return new Promise((resolve, reject) => {
            this.requestTableMethodName({
                ...this.searchParam,
                paging: this.paging,
            })
                .then((res: any) => {
                    this.tableData = res.list || [];
                    this.paging.total = res.total;
                    this.tableLoading = false;
                    resolve(res);
                })
                .catch(err => {
                    this.tableLoading = false;
                    reject(err);
                });
        });
    }

    // 点击行
    handleBtn(type: string, row: any) {
        if (type == 'look') {
            this.recordDetailVisible = true;
            this.curRecord = { type: 'lookStaticRiskDisposal', value: row };
            this.recordForm = {
                ...row,
                startTime: this.handleTime(row.startTime),
                sendDateTime: String(row.sendDate || '') + this.handleTime(row.sendTime),
                deliveryDateTime: String(row.sendDate || '') + this.handleTime(row.sendTime),
            };
            this.changeAccountControlValue(this.recordForm.noticeUser, 'noticeUser');
            this.changeAccountControlValue(this.recordForm.noticeCCuser, 'noticeCCuser');
            this.changeAccountControlValue(this.recordForm.notifier, 'notifier');
            console.log(this.recordForm, 'recordForm');
            // this.$emit('look-detail', this.curRecord);
        }
    }

    // 时间回显
    handleTime(time: any) {
        let timefor = '';
        if (time != undefined && time !== '') {
            timefor = String(time);
            // 补全时间格式
            if (String(time).length < 4) {
                for (let i = 0; i < 4 - String(time).length; i++) {
                    timefor = '0' + timefor;
                }
            }
        }
        return timefor;
    }
}
</script>
<style lang="scss" scoped>
.content {
    padding: 5px;
}
.noOpened /deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100vh - 270px) !important;
    }
    a {
        color: #578bec;
        padding: 0 5px;
    }
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    column-gap: 10px;
    .btn {
        display: flex;
    }
}

#header-query {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    /deep/ .el-form-item {
        margin-bottom: 4px;
        .el-form-item__label {
            color: black;
            padding-right: 2px;
        }
    }
}

/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
    display: flex;
    align-items: center;
    width: 65%;
    max-width: fit-content;
    padding-right: 5px;
    padding-left: 0px;
    margin: 2px 0 2px 2px;
    .el-select__tags-text {
        display: inline-block;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}
/deep/ .el-select__tags {
    flex-wrap: nowrap;
}
.record_detail /deep/ .el-select .el-tag__close.el-icon-close {
    display: none;
}
</style>
